import Bus from "~/utils/bus";
import { ElMessage } from "element-plus";

let cur_path = "/";
function file_api_get(path: string, offset: number) {
  cur_path = path.split("/").slice(0, -1).join("/");
  if (offset) Bus.emit("push.msg", { api: "get_file", data: { path, offset } });
  else Bus.emit("push.msg", { api: "get_file", data: { path } });
}

function file_api_get_path(path: string) {
  cur_path = path.split("/").slice(0, -1).join("/");
  Bus.emit("push.msg", { api: "get_files", data: { path } });
}

function file_api_search(path: string, name: string) {
  Bus.emit("push.msg", { api: "get_files_search", data: { path, name } });
  cur_path = path.split("/").slice(0, -1).join("/");
}

function file_api_create(path: string, isDir: Boolean) {
  let api = "create_file";
  if (isDir) api = "create_folder";
  cur_path = path.split("/").slice(0, -1).join("/");
  Bus.emit("push.msg", { api, data: { path } });
}

function file_api_delete(path: string, isDir: Boolean) {
  console.log("delete_file", path);
  let api = "delete_file";
  if (isDir) api = "delete_folder";
  cur_path = path.split("/").slice(0, -1).join("/");
  Bus.emit("push.msg", { api, data: { path } });
}

function file_api_rename(path: string, name: string) {
  cur_path = path.split("/").slice(0, -1).join("/");
  Bus.emit("push.msg", { api: "file_rename", data: { path, name } });
}

let is_uploading = false;
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
async function file_api_upload(data: any) {
  while (is_uploading) await sleep(500); // 休眠0.5秒
  is_uploading = true;
  console.log(data);
  file_api_create(data.path, false);
  Bus.emit("push.msg", {
    api: "change_file",
    data: { path: data.path, size: data.file.size },
  });
  const file = data.file;
  const chunkSize = 4 * 1024; // 分段大小 32K
  let offset = 0;
  let index = 0;
  while (offset < file.size) {
    const chunk = file.slice(offset, offset + chunkSize);
    const reader = new FileReader();
    reader.readAsArrayBuffer(chunk);
    await new Promise((resolve, rejuect) => {
      reader.onload = resolve;
      reader.onerror = rejuect;
    });
    const chunkData = reader.result;
    Bus.emit("push.msg", chunkData);
    offset += chunkSize;
    index++;
  }
  is_uploading = false;
}

export default {
  get: file_api_get,
  get_dir: file_api_get_path,
  search: file_api_search,
  delete: file_api_delete,
  rename: file_api_rename,
  upload: file_api_upload,
  create: file_api_create,
};
